package com.woniuxy.rabbit.config;

import com.alibaba.fastjson2.JSON;
import com.woniuxy.rabbit.pojo.FinanceMessage;
import com.woniuxy.rabbit.service.FinanceMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

/**
 * 消息的可靠投递
 */
@Component
@Slf4j
public class CallbackConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private FinanceMessageService messageService;

    /**
     * 初始化
     */
    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
        rabbitTemplate.setMandatory(true);//开启消息可靠投递
    }

    /**
     * 前提是开启消息可靠投递
     *消息不管成功失败，都会执行该方法
     *
     *
     * @param correlationData correlation data for the callback.消息相关的都可以拿到
     * @param ack true for ack, false for nack                  true：消息发送成功 false：失败
     * @param cause An optional cause, for nack, when available, otherwise null. 消息发送失败原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("消息发送成功，ack:{},失败原因:{}",ack,cause);
//        if(ack) return;//消息发送成功，直接返回

        //消息发送失败，进行消息补偿：
        // 重发（上限：10，每次间隔不一样）
        // 持久化到数据库，定时任务进行补偿（重发所需要的基本数据：消息体，交换机名称，路由键名称）
        byte[] body = correlationData.getReturnedMessage().getBody();
//        String msg = new String(body);
//        msg = JSON.parseObject(msg, String.class);
        String msg = JSON.parseObject(body, String.class);
        String receivedExchange = correlationData.getReturnedMessage().getMessageProperties().getReceivedExchange();
        String receivedRoutingKey = correlationData.getReturnedMessage().getMessageProperties().getReceivedRoutingKey();
        saveMessage(msg, receivedExchange, receivedRoutingKey,correlationData.getReturnedMessage().getMessageProperties().getAppId());


        // 人工处理（最终的解决方案）

    }

    /**
     * 前提是开启消息可靠投递
     * 消息发送失败，才会执行该方法
     *
     * @param message the returned message.
     * @param replyCode the reply code.
     * @param replyText the reply text.
     * @param exchange the exchange.
     * @param routingKey the routing key.
     */

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.error("消息发送失败，消息内容:{},失败原因:{},交换机:{},路由键:{}",message,replyText,exchange,routingKey);
        byte[] body = message.getBody();
        String appId = message.getMessageProperties().getAppId();
        saveMessage(JSON.parseObject(body, String.class), exchange, routingKey,appId);
    }

    private void saveMessage(String msg, String receivedExchange, String receivedRoutingKey,String appId) {
        FinanceMessage financeMessage =null;
        if(StringUtils.isEmpty(appId)){
            financeMessage = new FinanceMessage();
            financeMessage.setMessage(msg);
            financeMessage.setExchange(receivedExchange);
            financeMessage.setRoutingKey(receivedRoutingKey);
        }else {
            financeMessage = messageService.getById(appId);
            financeMessage.setState(2);
        }
        messageService.saveOrUpdate(financeMessage);
    }
}
